package com.song.service.role;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.song.common.Result;
import com.song.dao.role.RoleDao;
import com.song.dao.role.UserRoleDao;
import com.song.entity.role.Role;
import com.song.entity.role.UserRole;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao,Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public Result<List<Role>> selectRoleList(Role role, String startTime, String endTime, int pageNum, int pageSize) {
        Result<List<Role>> result = new Result<>();
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = new HashMap<>();
        map.put("roleName",role.getRoleName());
        map.put("status",role.getStatus());
        map.put("startTime",startTime);
        map.put("endTime",endTime);

        List<Role> roleList = roleDao.selectRoleList(map);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        result.setCode(0);
        result.setCount((int)pageInfo.getTotal());
        result.setData(roleList);
        return result;
    }

    @Override
    public Result<Integer> deleteRoleById(int roleId) {
        Result<Integer> result = new Result<>();
        roleDao.deleteRoleById(roleId);
        result.setCode(0);
        return result;
    }

    @Override
    public Result<Integer> batchDel(String[] array) {
        Result<Integer> result = new Result<>();
        roleDao.batchDel(array);
        result.setCode(0);
        return result;
    }




    /**
     * 新增角色
     */
    @Override
    public Result<Integer> addRole(Role role) {
        Result<Integer> result = new Result<>();
        role.setCreateTime(new Timestamp(System.currentTimeMillis()));
        role.setCreateAdmin("admin");
        roleDao.addRole(role);
        result.setCode(0);
        return result;
    }

    @Override
    public Result<Integer> updateRole(Role role) {
        Result<Integer> result = new Result<>();
        role.setUpdateAdmin("admin");
        roleDao.updateRole(role);
        result.setCode(0);
        return result;
    }

    /**
     * 获得整个角色树
     */
    @Override
    public JSONArray getRoleTree() {
        EntityWrapper ew = new EntityWrapper();
        ew.where("status={0}",0);
        ew.orderBy("order_num");
        List<Role> roles = roleDao.selectList(ew);
        JSONArray jsonArray = new JSONArray();
        if (roles != null && !roles.isEmpty()) {
            for (Role role : roles) {
                jsonArray.add(putSimpleRoleInfo(role));
            }
        }
        return jsonArray;
    }

    /**
     * 根据用户ID,获得角色树
     */
    @Override
    public JSONArray getRoleTreeByUserId(Integer userId) {
        // 所有角色列表
        EntityWrapper ew = new EntityWrapper();
        ew.where("status={0}",0);
        ew.orderBy("order_num");
        List<Role> roles = roleDao.selectList(ew);
        // 用户拥有的角色列表
        List<Integer> roleIds = userRoleDao.selectRoleIdsByUserId(userId);
        return getRoles(roles,roleIds);
    }


    /**
     * 角色树是否选中
     */
    public JSONArray getRoles(List<Role> roles, List<Integer> roleIds) {
        JSONArray array = new JSONArray();
        boolean checked = false;
        if (roles != null && !roles.isEmpty()) {
            for (Role role : roles) {
                if (roleIds != null && !roleIds.isEmpty()) {
                    checked = roleIds.contains(role.getRoleId());
                }
                array.add(putRoleInfo(role,checked));
            }
        }
        return array;
    }

    /**
     * 角色树节点信息
     */
    public JSONObject putRoleInfo(Role role,boolean checked) {
        JSONObject json = new JSONObject();
        json.put("id",role.getRoleId());
        json.put("name",role.getRoleName());
        json.put("pId",role.getFatherId());
        json.put("title",role.getRoleName());
        json.put("checked",checked);
        return json;
    }

    /**
     * 简单树节点数据
     */
    public JSONObject putSimpleRoleInfo(Role role) {
        JSONObject json = new JSONObject();
        json.put("id",role.getRoleId());
        json.put("name",role.getRoleName());
        json.put("pId",role.getFatherId());
        json.put("open",true);
        return json;
    }


    // layui tree
    @Override
    public JSONArray queryRoleTree() {
        EntityWrapper ew = new EntityWrapper();
        ew.where("status={0}",0);
        ew.orderBy("order_num");
        List<Role> roles = roleDao.selectList(ew);
        JSONArray jsonArray = new JSONArray();
        if (roles != null && !roles.isEmpty()) {
            for (Role role : roles) {
                jsonArray.add(getFatherNode(role));
            }
        }
        return jsonArray;
    }

    // 获得父节点
    public JSONObject getFatherNode (Role role) {
        JSONObject json =  getNodeInfo(role);
        json.put("children", getSubNode(role.getRoleId(),new JSONArray()));
        return json;
    }

    // 获得节点信息
    public JSONObject getNodeInfo (Role role) {
        JSONObject json = new JSONObject();
        json.put("name",role.getRoleName());
        json.put("id",role.getRoleId());
        json.put("spread",false);
        return json;
    }

    // 获得子节点信息
    public JSONArray getSubNode (int fatherId, JSONArray array) {
        List<Role> roles = roleDao.getRoleByFatherId(fatherId);
        if (roles != null || roles.size() > 0) {
            for (Role role : roles) {
                JSONObject json = getNodeInfo(role);
                json.put("children",getSubNode(role.getRoleId(),new JSONArray()));
                array.add(json);
            }
        }
        return array;
    }

}
